package com.flink.watermark;

import com.flink.func.WaterSensorMapFunction;
import com.flink.pojo.WaterSensor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import javax.annotation.Nullable;

/**
 * CustomPeriodicWatermarkDemo
 *
 * @author caizhiyang
 * @since 2024-02-28
 */
public class CustomPeriodicWatermarkDemo {
    public static void main(String[] args) throws Exception {
        //自定义水位线-周期性
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置水位线生成间隔时间为2秒
        env.getConfig().setAutoWatermarkInterval(2000);
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> ds = env.socketTextStream("localhost", 7777).map(new WaterSensorMapFunction());

        //设置自定义水位线生成策略
        ds.assignTimestampsAndWatermarks(new CustomWatermarkStrategy())
                .keyBy(w -> w.getId())
                //使用事件时间滚动窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        long startTs = context.window().getStart();
                        long endTs = context.window().getEnd();
                        String windowStart = DateFormatUtils.format(startTs, "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(endTs, "yyyy-MM-dd HH:mm:ss.SSS");
                        long count = elements.spliterator().estimateSize();
                        out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());
                    }
                }).print();

        env.execute();
    }

    public static class CustomWatermarkStrategy implements WatermarkStrategy<WaterSensor> {
        @Override
        public TimestampAssigner<WaterSensor> createTimestampAssigner(TimestampAssignerSupplier.Context context) {
            return new SerializableTimestampAssigner<WaterSensor>() {
                @Override
                public long extractTimestamp(WaterSensor element,long recordTimestamp) {
                    //TODO 1:从元素中提取水位线字段
                    return element.ts * 1000; // 告诉程序数据源里的时间戳是哪一个字段
                }
            };
        }

        @Override
        public WatermarkGenerator<WaterSensor> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
            //TODO 2:定义水位线生成策略
            return new CustomBoundedOutOfOrdernessGenerator();
        }
    }

    public static class CustomBoundedOutOfOrdernessGenerator implements WatermarkGenerator<WaterSensor> {

        private Long delayTime = 5000L; // 延迟时间
        private Long maxTs = Long.MIN_VALUE + delayTime + 1L; // 观察到的最大时间戳

        @Override
        public void onEvent(WaterSensor event,long eventTimestamp,WatermarkOutput output) {
            // 每来一条数据就调用一次
            maxTs = Math.max(eventTimestamp, maxTs); // 更新最大时间戳
        }

        @Override
        public void onPeriodicEmit(WatermarkOutput output) {
            // 发射水位线，默认200ms调用一次
            Watermark watermark = new Watermark(maxTs - delayTime - 1L);
            System.out.println(watermark.getTimestamp());
            output.emitWatermark(watermark);
        }
    }
}
